# client.py
import socket
import os
from cryptography.fernet import Fernet

KEY = b'2DArf8mfLdgsDgwdnBQ5Uzr9zIRSEVerCnVk8Mn9xTQ='
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 8080))
cipher = Fernet(KEY)


def send_file(file_path):
    try:
        file_size = os.path.getsize(file_path)
        file_name = os.path.basename(file_path)

        # 发送文件头（加密）
        header = f"FILE{SEPARATOR}{file_name}{SEPARATOR}{file_size}"
        encrypted_header = cipher.encrypt(header.encode())
        client_socket.send(encrypted_header)

        # 分块发送文件内容
        with open(file_path, "rb") as f:
            while True:
                bytes_read = f.read(BUFFER_SIZE)
                if not bytes_read:
                    break
                encrypted_data = cipher.encrypt(bytes_read)
                client_socket.send(encrypted_data)
        print(f"文件 {file_name} 发送完成")

    except Exception as e:
        print(f"文件发送失败: {str(e)}")


while True:
    message = input("输入消息（/sendfile 发送文件）：")

    if message.startswith("/sendfile"):
        _, file_path = message.split(" ", 1)
        if os.path.exists(file_path):
            send_file(file_path)
        else:
            print("文件不存在")
        continue

    # 普通消息处理
    encrypted_msg = cipher.encrypt(message.encode("utf-8"))
    client_socket.send(encrypted_msg)

    if message == "exit":
        break

    # 接收回复
    encrypted_data = client_socket.recv(BUFFER_SIZE)
    try:
        decrypted_data = cipher.decrypt(encrypted_data).decode("utf-8")
        print(f"服务器回复：{decrypted_data}")
    except:
        print("解密失败！连接已终止")
        break

client_socket.close()